//
//  SMPopupStandardView.swift
//  SomePasti
//
//  Created by 李永彬 on 2025/10/11.
//

import SwiftUI

struct SMPopupStandardView: View {
    let title: String?
    let message: String?
    let backgroundImage: String?
    let buttons: [SMPopupButton]
    
    // 私有常量
    private let horizontalPadding: CGFloat = 16
    private let verticalSpacing: CGFloat = 20
    private let titleTopPadding: CGFloat = 30
    private let titleMessageSpacing: CGFloat = 4
    private let buttonSpacing: CGFloat = 10
    private let buttonBottomPadding: CGFloat = 20
    
    var body: some View {
        VStack(spacing: 0) {
            contentSection
            buttonSection
        }
        .frame(height: calculateViewHeight())
    }
    
    // MARK: - 内容区域
    private var contentSection: some View {
        VStack(spacing: 0) {
            titleView
            messageView
        }
    }
    
    private var titleView: some View {
        Group {
            if let title = title {
                Text(title)
                    .font(.headline)
                    .foregroundColor(.white)
                    .multilineTextAlignment(.center)
                    .padding(.top, titleTopPadding)
                    .padding(.horizontal, horizontalPadding)
                Spacer()
                    .frame(height: 20)
                Spacer()
            }
        }
    }
    
    private var messageView: some View {
        Group {
            if let message = message {
                Text(message)
                    .font(.body)
                    .multilineTextAlignment(.center)
                    .foregroundColor(.black)
                    .padding(.top, title != nil ? titleMessageSpacing : verticalSpacing)
                    .padding(.horizontal, horizontalPadding)
                    .padding(.vertical, verticalSpacing)
            }
            Spacer()
        }
    }
    
    // MARK: - 按钮区域
    private var buttonSection: some View {
        Group {
            if !buttons.isEmpty {
                VStack(spacing: buttonSpacing) {
                    ForEach(Array(buttons.enumerated()), id: \.offset) { index, button in
                        button
                    }
                }
                .background(Color.clear)
                .padding(.horizontal, horizontalPadding)
                .padding(.bottom, buttonBottomPadding)
            }
        }
    }
    
    // MARK: - 高度计算
    private func calculateViewHeight() -> CGFloat {
        guard let backgroundImage = backgroundImage else {
            return calculateDynamicHeight()
        }
        
        return ImageUtility.proportionalHeight(for: backgroundImage,
                                               targetWidth: AppConstants.screenWidth - 2 * horizontalPadding)
    }
    
    private func calculateDynamicHeight() -> CGFloat {
        // 这里可以根据内容动态计算高度
        // 暂时返回0，让内容决定高度
        return 0
    }
}

